package demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import demo.util.HttpUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
public class LivenessController {
    final static String appcode = "您的阿里云AppCode";
    @GetMapping("/h5demo/liveness")
    public String showIdentityInfoPage() {
        String bizId = System.currentTimeMillis() + "_" + UUID.randomUUID().toString().replace("-", "");
        String host = "https://livenessh5.eshunda.cn";
        String path = "/getVerifyUrl";
        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + appcode);
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        headers.put("X-Ca-Nonce", UUID.randomUUID().toString());
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("bizType", "2");
        bodys.put("bizId", bizId);
        bodys.put("livingType", "23");
        bodys.put("returnUrl", "http://localhost:8080/h5demo/liveness/return-demo");
        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println("请求结果：" + response);
            String responseBody = EntityUtils.toString(response.getEntity());
            System.out.println("业务数据：" + responseBody);
            JSONObject jsonResponse = JSON.parseObject(responseBody);
            String resultResponseCode = jsonResponse.getString("code");
            if ("200".equals(resultResponseCode)) {
                Map<String, Object> data = (Map<String, Object>) jsonResponse.get("data");
                String verifyUrl = (String) data.get("verifyUrl");
                String orderNo = (String) data.get("orderNo");
                System.out.println("获取到订单号：" + orderNo);
                return "redirect:" + verifyUrl;
            } else {
                String errorMsg = "获取验证URL失败: " + jsonResponse.getString("msg");
                System.out.println(errorMsg);
                return "error";
            }
        } catch (Exception e) {
            System.out.println("发生异常: " + e.getMessage());
            return "error";
        }
    }
    
    @RequestMapping("/h5demo/liveness/return-demo")
    public String returnDemo(String result, Model model) {
        try {
            System.out.println("接收到的数据：" + result);
            JSONObject jsonObject = JSON.parseObject(result);
            String msg = jsonObject.getString("msg");
            String code = jsonObject.getString("code");
            String orderNo = jsonObject.getString("orderNo");
            String resultCode = "";
            String passed= "";
            String bestImgUrl = "" ;
            if (StringUtils.isNotBlank(orderNo)){
                String host = "https://livenessh5.eshunda.cn";
                String path = "/getResult";
                String method = "POST";
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Authorization", "APPCODE " + appcode);
                headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                headers.put("X-Ca-Nonce", UUID.randomUUID().toString());
                Map<String, String> querys = new HashMap<String, String>();
                Map<String, String> bodys = new HashMap<String, String>();
                bodys.put("orderNo", orderNo);
                try {
                    HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
                    System.out.println("请求结果：" + response);
                    String responseBody = EntityUtils.toString(response.getEntity());
                    System.out.println("业务数据：" + responseBody);
                    JSONObject jsonResponse = JSON.parseObject(responseBody);
                    String resultResponseCode = jsonResponse.getString("code");
                    if ("200".equals(resultResponseCode)) {
                        Map<String, Object> data = (Map<String, Object>) jsonResponse.get("data");
                         resultCode = (String)data.get("resultCode");
                         passed = (String)data.get("passed");
                         bestImgUrl = (String)data.get("bestImgUrl");
                    }
                } catch (Exception e) {
                    System.out.println("获取验证结果时发生异常：" + e.getMessage());
                }
            }
            model.addAttribute("code", code);
            model.addAttribute("msg", msg);
            model.addAttribute("resultCode", resultCode);
            model.addAttribute("passed", passed);
            model.addAttribute("bestImgUrl", bestImgUrl);
            return "liveness-result";
        } catch (Exception e) {
            System.out.println("JSON 解析失败: " + e);
            model.addAttribute("code", "500");
            model.addAttribute("msg", "数据解析失败");
            model.addAttribute("resultCode", "500");
            model.addAttribute("passed", "F");
            model.addAttribute("bestImgUrl", "");
            return "liveness-result";
        }
    }
}
